package com.lyf.emall.service.impl;

import com.lyf.emall.bean.LoginUser;
import com.lyf.emall.bean.SysAuthority;
import com.lyf.emall.bean.SysUser;
import com.lyf.emall.mapper.SysMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author Lfy
 * @Date 2022/2/15-13:29
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SysMapper sysMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        SysUser sysUser = sysMapper.querySysUserByUserName(username);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 根据用户查询权限信息 添加到LoginUser中
        List<String> authority = sysMapper.querySysAuthorityByRoleId(sysUser.getRoleId());
        // 封装成UserDetails对象返回
        LoginUser loginUser = new LoginUser(sysUser,authority);
        return loginUser;
    }
}
